package com.it.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.dao.CheckGroupDao;
import com.it.entity.PageResult;
import com.it.entity.QueryPageBean;
import com.it.pojo.CheckGroup;
import com.it.pojo.CheckItem;
import com.it.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService{
    /**
     * 检查组服务
     */
    @Autowired
    private CheckGroupDao checkGroupDao;

    //添加检查组 同时需要设置检查组合和检查项的关联关系
    public void add(CheckGroup checkGroup ,Integer[] checkitemIds){
        checkGroupDao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }

    //设置检查组合和检查项的关联关系
    public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds){
        if(checkitemIds != null && checkitemIds.length > 0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("checkgroup_id",checkGroupId);
                map.put("checkitem_id",checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
    //检查组分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean){
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());

    };
    //根据id检查组信息
    public CheckGroup findById(Integer id){
        CheckGroup checkGroup = checkGroupDao.findById(id);
        return checkGroup;

    }
    // 根据检查组id查询检查项
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id){
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);

    }

    //编辑
    public void edit(CheckGroup checkGroup,Integer[] checkitemIds){
        checkGroupDao.deleteAssociation(checkGroup.getId());
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
        //跟新检查组基本信息
        checkGroupDao.edit(checkGroup);

    }

    //检查组查询所有
    public List<CheckGroup> findAll(){
        return checkGroupDao.findAll();

    }
    //删除检查组
    public void deleteById(Integer id){
//        System.out.println("删除检查组与检查项关联表-------------------");


        checkGroupDao.deleteCheckItemIdsByCheckGroupId(id);
//        System.out.println("删除检查组与检查项关联表成功**************");
        checkGroupDao.deleteById(id);
//        System.out.println("删除检查组成功***********////");

    }


}
